#! /usr/bin/env python

# This file controls player hands - adding cards to hands, removing cards
# and drawing cards

import os
import pygame

class Hands (pygame.sprite.Sprite):
    def __init__ (self, player):
        pygame.sprite.Sprite.__init__(self)

        # Variables
        self.hand_size     = 0
        self.max_hand_size = 5
        self.player        = player
        self.hand_list     = []
        self.x             = 150
        self.rightx        = 230
        self.y             = 0
        self.bottomy       = 0
        self.image         = pygame.image.load(
            os.path.join ('data/images/Cards', 'HandCard.png')).convert_alpha()
        self.rect          = self.image.get_rect ()
        self.mouse_x       = 0
        self.mouse_y       = 0
        self.mouse_over    = False
        self.clicked_on_deck   = False
        self.screen        = None
        self.master_container = None

        self.DefinePlayerHandCoords ()

    def AddCard (self, card):
        # This function adds a card to the players hand.
        self.hand_list.append (card)
        self.hand_list[-1].player = self.player
        self.hand_list[-1].location = 1
        self.UpdateHandCardCoords ()
        self.SetHandSize ()

    def CheckHandSize (self):
        size = len(self.hand_list)
        return size

    def DefinePlayerHandCoords (self):
        self.y = (self.player - 1) * 170
        self.bottomy = self.y + 100
        self.rect.topleft = (self.x, self.y)

    def EndOfTurn (self):
        # This function is called at the end of a player's turn.
        # It checks to see if the player has to discard, and if so
        # creates a list that stores the cards needing to be discarded.
        # Then, it sees if the player is the lowest level player. If the
        # player is, the cards are sent to the discard pile.
        # If the player is not, then the cards are given to the lowest level
        # player/players.
        if self.CheckHandSize () > self.max_hand_size:
            # Player is over the limit on cards. Need to discard.
            tempList = []
            while self.CheckHandSize () > self.max_hand_size:
                print ("\nYou are over the limit on the number of cards in" +
                "your hand. Please pick a card to discard.")
                for num in range(len(self.hand_list)):
                    print "%d: %s" % (num, self.hand_list[num].title)
                inp = raw_input (": ")
                try:
                    inp = int (inp)
                    try:
                        print "Trying to discard card number %d" % inp
                        card = self.hand_list[inp]
                        tempList.append (card)
                        self.RemoveCard(card)
                    except:
                        print "%s is not a valid number input. Try again." % input
                except:
                    pass
            print "\nHere are the cards being discarded:"
            for num in range(len(tempList)):
                print "%d: %s" % (num, tempList[num].title)

            # Here is where I check to see if the player is the lowest level player.
            lowestLevel = 10
            lplayer = []
            if self.master_container[4].character_level < lowestLevel:
                lowestLevel = self.master_container[4].character_level
                lplayer.append (self.master_container[4])
                
            if self.master_container[7].character_level == lowestLevel:
                lplayer.append (self.master_container[7])
            elif self.master_container[7].character_level < lowestLevel:
                lowestLevel = self.master_container[7].character_level
                lplayer = []
                lplayer.append (self.master_container[7])
                
            if self.master_container[10].character_level == lowestLevel:
                lplayer.append (self.master_container[10])
            elif self.master_container[10].character_level < lowestLevel:
                lplayer = []
                lowestLevel = self.master_container[10].character_level
                lplayer.append (self.master_container[10])
                
            if self.master_container[13] != None:
                if self.master_container[13].character_level == lowestLevel:
                    lplayer.append (self.master_container[13])
                elif self.master_container[13].character_level < lowestLevel:
                    lplayer = []
                    lowestLevel = self.master_container[13].character_level
                    lplayer.append (self.master_container[13])
                    
            if self.master_container[16] != None:
                if self.master_container[16].character_level == lowestLevel:
                    lplayer.append (self.master_container[16])
                elif self.master_container[16].character_level < lowestLevel:
                    lplayer = []
                    lowestLevel = self.master_container[16].character_level
                    lplayer.append (self.master_container[16])

            if self.master_container[19] != None:
                if self.master_container[19].character_level == lowestLevel:
                    lplayer.append (self.master_container[19])
                if self.master_container[19].character_level < lowestLevel:
                    lplayer = []
                    lowestLevel = self.master_container[19].character_level
                    lplayer.append (self.master_container[19])

            # Now I know what the lowest level is (lowestLevel) and who is
            # that level (lplayer and lplayer2)
            # Check to see if this player is the lowest or tied for lowest
            found = False
            for p in lplayer:
                if self.player == p.player:
                    found = True
                    # This player is the lowest level. Thus, the cards are sent
                    # to the discard pile rather than another player.
                    for num in range(len (tempList)):
                        print "Sending %s to the discard deck." % tempList[num].title
                        # Send the card to discard pile.
                        self.master_container[1].AddCard (tempList[num])
                    break
            if found == False:
                # Current player is not the lowest level. Thus, the cards need to
                # be divided among the lowest level players.
                # One or two people to divide among.
                count = 0
                playerHands = {1: self.master_container[5],
                               2: self.master_container[8],
                               3: self.master_container[11],
                               4: self.master_container[14],
                               5: self.master_container[17],
                               6: self.master_container[20]}
                for card in tempList:
                    try:
                        print 'Sending %s to player %s.' % (card.title, lplayer[count])
                        playerHands[lplayer[count].player].AddCard(card)
                        count = count + 1
                    except:
                        # count is too high, resetting to 0.
                        count = 0
                        print 'Sending %s to player %s.' % (card.title, lplayer[count])
                        playerHands[lplayer[count].player].AddCard(card)
                        count = count + 1                    
        else:
            # Player is not over the limit.
            pass

    def GetHandSize (self):
        return self.hand_size

    def PrintData (self):
        print '''\n
Hand of Player:    %d
Max Hand Size:     %d
Current Hand Size: %d
\n''' % (self.player, self.max_hand_size, self.hand_size)

    def RemoveCard (self, card):
        position = self.hand_list.index (card)
        tempcard = self.hand_list.pop (position)
        self.UpdateHandCardCoords ()
        self.SetHandSize ()
        return tempcard

    def SetHandSize (self):
        self.hand_size = len(self.hand_list)

    def SetupMasterContainer (self, master_container):
        self.master_container = master_container
        self.screen = self.master_container[22]

    def Update (self, mouse_x, mouse_y, mouse_click):
        self.screen.blit (self.image, self.rect)
        self.mouse_over = False

        # Is mouse over the player hand icon
        if ((mouse_x > self.x) and (mouse_y > self.y) and
               (mouse_x < self.rightx) and (mouse_y < self.bottomy)):
            self.mouse_over = True
            # Draw sparkles
            s = self.master_container [23]
            s(self.x, self.rightx, self.y, self.bottomy)
            if mouse_click:
                self.PrintData ()
                if self.clicked_on_deck:
                    self.clicked_on_deck = False
                else:
                    self.clicked_on_deck = True

    def UpdateHandCardCoords (self):
        # This function tells the cards in this persons hand that they are in
        # a hand. This makes them draw differently than if the cards were out
        # on the table and such
        draw_pos = [(0, 250), (100,250), (200,250), (300,250), (400,250),
                    (500,250), (600,250), (700, 250), (800,250)]
        x=0
        for card in self.hand_list:
            card.SetRectTopLeft(draw_pos[x])
            x+=1
